package cn.cpf.app.comp;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JLabel;

/**
 * <b>Description : </b>
 *
 * @author CPF
 * Date: 2020/5/7 10:04
 */
public class LinkLabel extends JLabel {
    private static final long serialVersionUID = 1L;

    private String text;

    private URL link = null;

    private Color preColor = null;

    public LinkLabel(String vText, String vLink) {
        super("<html>" + vText + "</html>");
        this.text = vText;
        try {
            if (!vLink.startsWith("http://"))
                vLink = "http://" + vLink;
            this.link = new URL(vLink);
        } catch (MalformedURLException err) {
            err.printStackTrace();
        }
        addMouseListener(new MouseAdapter() {
            public void mouseExited(MouseEvent e) {
                LinkLabel.this.setCursor(
                        Cursor.getPredefinedCursor(0));
                if (LinkLabel.this.preColor != null)
                    LinkLabel.this.setForeground(LinkLabel.this.preColor);
                LinkLabel.this.setText("<html>" + LinkLabel.this.text + "</html>");
            }

            public void mouseEntered(MouseEvent e) {
                LinkLabel.this.setCursor(
                        Cursor.getPredefinedCursor(12));
                LinkLabel.this.preColor = LinkLabel.this.getForeground();
                LinkLabel.this.setForeground(Color.BLUE);
                LinkLabel.this.setText("<html><u>" + LinkLabel.this.text + "</u></html>");
            }

            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(LinkLabel.this.link.toURI());
                } catch (IOException err) {
                    err.printStackTrace();
                } catch (URISyntaxException err) {
                    err.printStackTrace();
                }
            }
        });
    }
}
